//
//  JDOutlandSalesViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/4/2.
//

import UIKit
/// 境外直销
class JDOutlandSalesViewController: JDBaseViewController {
    
    var customTitleView: CustomTitleView?
    /// 原来是区分 跨境直销和境外预售的  暂时无用
    var titleType: String = "4"
    /// 国家
    var countryCollectionView: UICollectionView?
    var countryModels: [JDCountryInfoModel?]?
//    var countryName = ["全部","日本","韩国","泰国"]
//    var countryCode = ["all","jp","kr","th"]
    // 选中的分类的code
    var categoryCode = ""
    var countrySelectedIndex = 0
//    var countryImage = ["country_all","country_ja-jp","country_ ko-kr","country_en-th"]
    var needRefreshClassification = true
    
    /// 分类部分
    var classificationView: DraClassicHeadView?
    var goodsTypeTitleList: [String] = ["全部"]
    var goodsTypeModels :[JDGoodsTypeModel?]?
    /// 商品列表
    var mainTableView: UITableView?
    var goodsModels: [JDGoodsModel?]?
    
    var gradientView: UIView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.removeSeparatorLine()
        self.setupConfig()
        self.setupUIElements()
        
        self.getCountryCodeList()
        self.getClassificationData()
        self.getNetData(true)
        

//        let guide = view.safeAreaLayoutGuide
//        let bottomConstraint = view.bottomAnchor.constraint(equalTo: guide.bottomAnchor)
//        bottomConstraint.isActive = true
        
        // Do any additional setup after loading the view.
        
        
        self.createShopcartButton()
        
    }
    
    func createShopcartButton() {
        let shopcartButtonContainerView = UIView()
        self.view.addSubview(shopcartButtonContainerView)
        shopcartButtonContainerView.snp.makeConstraints { make in
            make.right.equalTo(self.view).offset(-12)
            make.bottom.equalTo(self.view).offset(-142)
            make.size.equalTo(CGSize(width: 64, height: 64))
        }
        shopcartButtonContainerView.makeCorner(4)
        shopcartButtonContainerView.backgroundColor = .white
        
        let imageV = UIImageView(image: UIImage.init(named: "red_shopcart"))
        shopcartButtonContainerView.addSubview(imageV)
        imageV.snp.makeConstraints { make in
            make.centerX.equalTo(shopcartButtonContainerView)
            make.top.equalTo(shopcartButtonContainerView).offset(8)
            make.size.equalTo(CGSizeMake(30, 30))
        }
        
        let titleLabel = UILabel()
        shopcartButtonContainerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(imageV.snp.bottom).offset(2)
            make.height.equalTo(17)
            make.centerX.equalTo(shopcartButtonContainerView)
        }
        titleLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        titleLabel.text = "购物车"
        
        let shopcartControl = UIControl(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
        shopcartButtonContainerView.addSubview(shopcartControl)
        shopcartControl.addTarget(self, action: #selector(gotoShopCartVC), for: .touchUpInside)
        
        shopcartButtonContainerView.makeBorder(color("#F5F6F8"), 0.5)
    }
    
    @objc func gotoShopCartVC() {
        
        if !JDTools.checkToken() {
            return
        }
        
        let shopcartVC = JDShopcartViewController()
        self.hidesBottomBarPushViewController(shopcartVC)
    }
    
    override func addObservers() {
        super.addObservers()
        NotificationCenter.default.addObserver(self, selector: #selector(notificationRefreshAction), name: Notification.Name("notificationRefresh"), object: nil)
    }
    
    @objc func notificationRefreshAction() {
        self.goodsModels?.removeAll()
        self.getClassificationData()
    }
    
    
    func setupConfig() {
//        self.customLeftBarButtonItem("xlbLogo", #selector(leftButtonAction), self)
        self.customImageLeftBarButtonItem("xlbLogo", #selector(leftButtonAction), self)
        
        self.customTitleView = CustomTitleView.init(frame: CGRect.init(x: 0, y: 0, width: 177, height: 44))
        self.customTitleView?.myDelegate = self
//        self.navigationItem.titleView = self.customTitleView
        self.changeTitleView(self.customTitleView)
        
        self.customImageRightBarButtonItem("nav_seach", #selector(searchButtonAction), self)
        
        self.goodsModels = [JDGoodsModel]()
        
        self.view.backgroundColor = color("#F5F6F8")
        
//        NotificationCenter.default.addObserver(self, selector: #selector(orderButtonAction), name: NSNotification.Name("gotoOrderList"), object: nil)
        
    }
    
    @objc func leftButtonAction() {
    }
    
    @objc func orderButtonAction() {
        if !JDTools.checkToken() {
            return;
        }
        let orderList = JDOrderListViewController()
        self.hidesBottomBarPushViewController(orderList)
    }
    
    @objc func searchButtonAction() {
        
        if !JDTools.checkToken() {
            return
        }
        
        printLog("搜索按钮")
        
        let searchVC = JDSearchViewController()
        searchVC.modalPresentationStyle = .none
        let navSearchVC = UINavigationController(rootViewController: searchVC)
        self.presentVC(navSearchVC)
        
    }
    
    func setupUIElements() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        
        self.countryCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        self.view.addSubview(self.countryCollectionView!)
        self.countryCollectionView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)//.offset(UIDevice().safeAreaInset.top)
            make.height.equalTo(102)
        })
        self.countryCollectionView?.delegate = self
        self.countryCollectionView?.dataSource = self
        self.countryCollectionView?.backgroundColor = .clear
        self.countryCollectionView?.register(JDCountryCollectionViewCell.self, forCellWithReuseIdentifier: "countryCell")
        
        let moreBgView = UIView()
        self.view.addSubview(moreBgView)
        moreBgView.backgroundColor = .white
        moreBgView.snp.makeConstraints { make in
            make.right.equalTo(self.view)
            make.top.equalTo(self.countryCollectionView!.snp.bottom).offset(9)
            make.width.equalTo(80)
            make.height.equalTo(44)
        }
        moreBgView.makeCorner(7)
        
        let memberButton = UIButton(type: .custom)
        self.view.addSubview(memberButton)
        memberButton.snp.makeConstraints { make in
            make.top.equalTo(self.countryCollectionView!.snp.bottom).offset(9+7)
            make.left.equalTo(self.view)
            make.size.equalTo(CGSizeMake(79, 37))
        }
        memberButton.setImage(UIImage(named: "member_button")?.withRenderingMode(.alwaysOriginal), for: .normal)
        memberButton.addTarget(self, action: #selector(memberAreaAction), for: .touchUpInside)
        
        let moreButton = UIButton(type: .custom)
        self.view.addSubview(moreButton)
        moreButton.snp.makeConstraints { make in
            make.right.equalTo(self.view).offset(-10)
            make.top.equalTo(self.countryCollectionView!.snp.bottom).offset(9+11)
            make.size.equalTo(CGSizeMake(46, 28))
        }
        moreButton.setTitle("分类", for: .normal)
        moreButton.setImage(UIImage(named: "arrow_black"), for: .normal)
        
        moreButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .regular)
        moreButton.setTitleColor(color("#333333"), for: .normal)
        moreButton.semanticContentAttribute = .forceRightToLeft
        moreButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 4)
        moreButton.addTarget(self, action: #selector(moreButtonAction), for: .touchUpInside)
    
        self.classificationView = DraClassicHeadView.init(CGRect(x: 0, y: 0, width: screenWidth-79-56, height: 44), titles: self.goodsTypeTitleList, index: 0)
        self.view.addSubview(self.classificationView!)
        self.classificationView?.snp.makeConstraints({ make in
            make.left.equalTo(memberButton.snp.right)
            make.right.equalTo(moreButton.snp.left)
            make.top.equalTo(self.countryCollectionView!.snp.bottom).offset(9)
//            make.height.equalTo(40)
            make.height.equalTo(44)
        })
        
        self.classificationView?.delegate = self
        self.classificationView?.backgroundColor = .white
        self.classificationView?.makeCorner(7)
        
        
        //        DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
        //            self.classificationView?.updateData(["中国","外国","我们啊","什么","怎么办呢","这个是啥","太短了嘛","还有问题吗"], index: 0)
        //        }
        
        self.gradientView = UIView()
        self.view.addSubview(self.gradientView!)
        self.gradientView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.classificationView!).offset(7)
            make.height.equalTo(240)
        })
        self.gradientView?.backgroundColor = .verticalGradientColor(topColor: .white, bottomColor: color("#F5F6F8"), colorFrame: CGRectMake(0, 0, screenWidth, 240))
        
        self.view.insertSubview(self.gradientView!, belowSubview: self.classificationView!)
        
        
        self.view.insertSubview(memberButton, aboveSubview: self.gradientView!)
        self.view.insertSubview(moreButton, aboveSubview: self.gradientView!)
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.top.equalTo(self.classificationView!.snp.bottom).offset(9)
        })
//        self.mainTableView?.backgroundColor = color("#F5F6F8")
        self.mainTableView?.backgroundColor = .clear
        self.mainTableView?.separatorStyle = .none
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.register(JDGoodsListCell.self, forCellReuseIdentifier: "mainTableViewCell")
        
        self.mainTableView?.addRefreshHeader { [weak self] in
            if self?.needRefreshClassification ?? true {
                self?.getClassificationData()
            }
            self?.currentPage = 1
            self?.getNetData(true)
        }
        
        self.mainTableView?.addRefreshFooter { [weak self] in 
            self?.currentPage += 1
            self?.getNetData(false)
        }

        self.setupTableViewEmptyView(self.mainTableView, offsetY: 50)
    }
        
    @objc func memberAreaAction() {
        if !JDTools.checkToken() {
            return 
        }
        let memberAreaVC = JDMemberAreaViewController()
        memberAreaVC.goodsModels = self.goodsModels
        memberAreaVC.goodsTypeModels = self.goodsTypeModels
        self.hidesBottomBarPushViewController(memberAreaVC)
    }
    
    @objc func moreButtonAction() {
        if !JDTools.checkToken() {
            return
        }
        let classilicationVC = JDClassificationViewController()
        classilicationVC.goodsTypeModels = self.goodsTypeModels
        self.hidesBottomBarPushViewController(classilicationVC)
        classilicationVC.selectedClassificationCompleted = {[weak self] classificationIndex ,selectedId in
            guard let classificationId = selectedId else { return }
            guard let weakSelf = self else { return }
            weakSelf.classificationView?.updateData(weakSelf.goodsTypeTitleList, index: classificationIndex+1)
            weakSelf.categoryCode = classificationId
            weakSelf.currentPage = 1
            weakSelf.getNetData(true)
        }
    }
    
    
    @objc func getClassificationData() {
        
        JDNetWorkRequest(.getGoodsType([:])) { responseStr in
            
            printLog("分类信息:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDGoodsTypeModel].deserialize(from: responseStr, designatedPath: "data") {
                    self.needRefreshClassification = false 
                    self.goodsTypeModels = models
                    self.goodsTypeTitleList = ["全部"]
                    for typeModel in models {
                        self.goodsTypeTitleList.append(typeModel?.name ?? "异常")
                    }
                    self.categoryCode = models.first??.pid ?? "0"
                    DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
                        self.classificationView?.updateData(self.goodsTypeTitleList, index: 0)
                    }
                }
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
    func getCountryCodeList() {
        JDNetWorkRequest(.getCountryCodeList) { responseStr in
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                
                
                if let models = [JDCountryInfoModel].deserialize(from: responseStr, designatedPath: "data") {
                    
                    self.countryModels = models
                    self.countryCollectionView?.reloadData()
                    printLog("我已经请求成功:\(models)")
                    
//                    if isRefresh {
//                        self.goodsModels = models
//                    } else {
//                        self.goodsModels?.append(contentsOf: models)
//                    }
//                    
//                    if models.count < 10 {
//                        self.mainTableView?.noMoreData()
//                    }
                } else {
                    self.view.toast(message: "异常数据")
                }
            } else {
                self.view.toast(message: commonModel?.msg ?? "网络异常")
            }
            
            
            
        } failure: { error in
            
        } error: { errorCode in
            
        }

    }
    
    override func getNetData(_ isRefresh: Bool = true) {
        
        var params = [String: Any]()
        // 国家代码
        params["countryCode"] = self.countryModels?[self.countrySelectedIndex]?.countryCode//self.countryCode[self.countrySelectedIndex]
        // 商品分类 -- 这个还要改
        if self.categoryCode.count > 0 {
            params["goodsCategory"] = self.categoryCode
        }
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        params["goodsMemberLevel"] = 1
        if isRefresh {
            self.goodsModels?.removeAll()
        }
        self.showLoading()
        print("商品列表接口:\(params)")
        JDNetWorkRequest(.getGoodsList(params)) { responseStr in
            self.dismissLoading()
            printLog("商品列表信息:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDGoodsModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    
                    if isRefresh {
                        self.goodsModels = models
                    } else {
                        self.goodsModels?.append(contentsOf: models)
                    }
                    
                    if models.count < 10 {
                        self.mainTableView?.noMoreData()
                    }
                } else {
                    self.view.toast(message: "异常数据")
                }
            } else {
                self.view.toast(message: commonModel?.msg ?? "网络异常")
            }
            self.mainTableView?.reloadData()
//            self.mainTableView?.ly_endLoading()
            self.mainTableView?.endRefresh()
            
        } failure: { error in
            self.view.toast(message: "网络异常")
            self.dismissLoading()
        } error: { errorCode in
            self.view.toast(message: "网络异常")
            self.dismissLoading()
        }

    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDOutlandSalesViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.countryModels?.count ?? 0
//        return self.countryName.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "countryCell", for: indexPath) as? JDCountryCollectionViewCell
        
        let currentModel = self.countryModels?[indexPath.item]
        
        let countryNameStr = currentModel?.countryName//self.countryName[indexPath.item]
        let countryImageStr = currentModel?.countryFlag //self.countryImage[indexPath.item]

        cell?.countryName?.text = countryNameStr
        cell?.countryImgV?.kf.setImage(with: URL(string: countryImageStr ?? ""), placeholder: nil, options: nil, completionHandler: nil)
//        cell?.countryImgV?.image = UIImage(named: countryImageStr)
        
        if self.countrySelectedIndex == indexPath.item {
            cell?.countryName?.textColor = color("#FA6161")
            cell?.countryImgV?.makeBorder(.red,1)
        } else {
            cell?.countryName?.textColor = color("#333333")
            cell?.countryImgV?.makeBorder(.white,1)
        }
        
        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 7, bottom: 0, right: 7)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (floor(screenWidth-14-1)/4.0), height: 102)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0.01
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0.01
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.countrySelectedIndex = indexPath.item
        collectionView.reloadData()
//        collectionView.ly_endLoading()
        self.currentPage = 1
        self.getNetData(true)
    }
    
}
 
extension JDOutlandSalesViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.goodsModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mainTableViewCell") as? JDGoodsListCell
        cell?.contentView.backgroundColor = .clear
        cell?.selectionStyle = .none
        let goodsModel = self.goodsModels?[indexPath.row]
        cell?.goodsModel = goodsModel
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 97+10
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let goodsModel = self.goodsModels?[indexPath.row] else {
            return
        }
        let goodsDetailVC = JDGoodsDetailViewController()
        goodsDetailVC.goodsLogoUrl = goodsModel.goodsMainImgUrl
        goodsDetailVC.goodsID = goodsModel.goodsId
        self.hidesBottomBarPushViewController(goodsDetailVC)
    }
}

extension JDOutlandSalesViewController: DraClassicHeadViewDelegate {
    func didSelectTitleAt(_ index: Int) {
        if index == 0 {
            self.categoryCode = ""
        } else {
            let selectedModel = self.goodsTypeModels?[index-1]
            self.categoryCode = selectedModel?.id ?? ""
        }
        print("这个的内容:\(self.categoryCode)")
        self.currentPage = 1
        self.getNetData(true)
    }
}

extension JDOutlandSalesViewController: CustomTitleViewDelegate {
    func customTitleDidSelected(at index: Int) {
//        if index == 0 {
//            self.titleType = "4"
//        } else if index == 1 {
//            self.titleType = "5"
//        }
        self.currentPage = 1
        self.getNetData(true)
    }
}
